import { Component, Output, EventEmitter, Input, ViewContainerRef, ElementRef, ViewChildren, QueryList } from '@angular/core';
import { FilterSettingModel } from './models/filterSetting.model';
import { FilterSettingOptionModel } from './models/filterSettingOption.model';
import { SelectDropDownComponent } from 'ngx-select-dropdown';

@Component({
    selector: 'app-landing-page-filter',
    templateUrl: './landing-page-filter.component.html',
    styleUrls: ['./landing-page-filter.component.scss']
})
export class LandingPageFilterComponent {
    public selected: any = {};

    public multiSelect: any[] = [];

    @Input() settings: FilterSettingModel[];

    @Output() apply: EventEmitter<any> = new EventEmitter<any>();

    @ViewChildren(SelectDropDownComponent) selectors: QueryList<SelectDropDownComponent>;

    constructor(public vcRef: ViewContainerRef) { }

    public changeValue(setting: string, event: any) {
        this.selected[setting] = event.value.slice(); //clone array so operations not to affect the drop down options
        this.updateSelected();
        this.sortOptions(setting);        
    }

    public mathMin(first: number, second: number): number{
        return Math.min(first, second);
    }
    public removeCriteria(criteria: FilterSettingOptionModel) {        
        this.selected[criteria.parentList].splice(this.selected[criteria.parentList].findIndex(x => x._id == criteria._id), 1);
        this.updateSelected();
        this.sortOptions(criteria.parentList, criteria);        
    }

    private updateSelected() {
        let newSelected: any[] = [];
        Object.keys(this.selected).forEach(field => {
            newSelected = newSelected.concat(this.selected[field]);
        });
        this.multiSelect = newSelected;
    }

    private sortOptions(setting: string, deselectCriteria: FilterSettingOptionModel = null){
        let selector = this.selectors.find(x => x.config.setting == setting) as SelectDropDownComponent;
        if(deselectCriteria != null)
            selector.deselectItem(deselectCriteria, selector.selectedItems.findIndex(x => x._id == deselectCriteria._id));
        selector.availableItems = (selector.availableItems as any[]).sort(function (a, b) { return a.index - b.index });
    }

    public filter() {
        //send only selection IDs andn ot other details
        let ret = {};
        Object.keys(this.selected).forEach(element => {
            ret[element] = this.selected[element].map(x => x._id);
        });
        this.apply.emit(ret);
    }
}
